from typing import List, Literal, Optional, Dict, Any
import asyncio
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urljoin, urlparse
from pydantic import ConfigDict, Field, HttpUrl
from atomic_agents.agents.base_agent import BaseIOSchema
from atomic_agents.lib.base.base_tool import BaseTool, BaseToolConfig
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))
from BasicTools.BehaviorQuantModel.ChatRecordProcessor import ChatRecordProcessor
from BasicTools.BehaviorQuantModel.DataModels import ChatRecord
class GetChatRecordInputSchema(BaseIOSchema):
    """Input schema for GetChatRecord tool."""
    model_config = ConfigDict(
        json_schema_extra={
            "example": {
                "user_id": "user_001",
                "question_id": "q001"
            }
        }
    )
    user_id: str = Field(
        ...,
        description="The ID of the user to get chat record for.",
        examples="user_001"
    )
    question_id: str = Field(
        ...,
        description="The ID of the question to get chat record for.",
        examples="q001"
    )
    agent_type: str = Field(
        default="attack",
        description="The type of agent to get chat record for (attack or defense).",
        examples="attack"
    )
class GetChatRecordOutputSchema(BaseIOSchema):
    """Output schema for GetChatRecord tool."""
    model_config = ConfigDict(
        json_schema_extra={
            "example": {
                "chat_record": {
                    "user_id": "user_001",
                    "question_id": "q001",
                    "messages": [
                        {
                            "message_id": "msg_001",
                            "user_id": "user_001",
                            "question_id": "q001",
                            "message_type": "user",
                            "content": "我需要帮助解决这个问题",
                            "timestamp": "2025-01-15T10:30:00Z",
                            "is_helpful": None
                        },
                        {
                            "message_id": "msg_002",
                            "user_id": "user_001",
                            "question_id": "q001",
                            "message_type": "assistant",
                            "content": "我来帮助您解决这个问题。首先，让我们分析一下...",
                            "timestamp": "2025-01-15T10:30:15Z",
                            "is_helpful": True
                        }
                    ],
                    "total_messages": 2,
                    "conversation_duration": "0:15:30"
                },
                "formatted_chat": "=== 聊天记录 ===\n用户ID: user_001\n问题ID: q001\n...",
                "statistics": {
                    "total_messages": 2,
                    "user_messages": 1,
                    "assistant_messages": 1,
                    "conversation_duration": "0:15:30",
                    "avg_message_length": {
                        "user": 25.5,
                        "assistant": 48.2
                    }
                }
            }
        }
    )
    chat_record: ChatRecord = Field(
        ...,
        description="The structured chat record data.",
        examples={
            "user_id": "user_001",
            "question_id": "q001",
            "messages": [
                {
                    "message_id": "msg_001",
                    "user_id": "user_001",
                    "question_id": "q001",
                    "message_type": "user",
                    "content": "我需要帮助解决这个问题",
                    "timestamp": "2025-01-15T10:30:00Z",
                    "is_helpful": None
                },
                {
                    "message_id": "msg_002",
                    "user_id": "user_001",
                    "question_id": "q001",
                    "message_type": "assistant",
                    "content": "我来帮助您解决这个问题。首先，让我们分析一下...",
                    "timestamp": "2025-01-15T10:30:15Z",
                    "is_helpful": True
                }
            ],
            "total_messages": 2,
            "conversation_duration": "0:15:30",
            "user_satisfaction": 0.8
        }
    )
    formatted_chat: str = Field(
        ...,
        description="The formatted chat record for display.",
        examples="=== 聊天记录 ===\n用户ID: user_001\n问题ID: q001\n消息总数: 2\n对话持续时间: 0:15:30\n用户满意度: 80.00%\n\n=== 对话内容 ===\n[2025-01-15T10:30:00] 🧑 用户:\n  我需要帮助解决这个问题\n\n[2025-01-15T10:30:15] 🤖 助手:\n  我来帮助您解决这个问题。首先，让我们分析一下...\n  (✅ 有用)\n"
    )
    statistics: Dict[str, Any] = Field(
        ...,
        description="Statistical information about the chat record.",
        examples={
            "total_messages": 2,
            "user_messages": 1,
            "assistant_messages": 1,
            "conversation_duration": "0:15:30",
            "user_satisfaction": 0.8,
            "avg_message_length": {
                "user": 25.5,
                "assistant": 48.2
            }
        }
    )
class GetChatRecordTool(BaseTool):
    """
    Tool to get chat record for a specific user and question. 
    It uses the ChatRecordProcessor to retrieve and format chat records.
    Returns structured chat data, formatted display text, and statistics.
    """
    name = "GetChatRecord"
    description = "Get the chat record for a specific user and question."
    input_schema = GetChatRecordInputSchema
    output_schema = GetChatRecordOutputSchema
    processor: ChatRecordProcessor
    def run(self, input: GetChatRecordInputSchema) -> GetChatRecordOutputSchema:
        self.processor = ChatRecordProcessor()
        # 获取聊天记录
        chat_record = self.processor.get_formatted_chat_record(
            input.user_id, 
            input.question_id,
            input.agent_type
        )
        # 格式化显示
        formatted_chat = self.processor.format_chat_for_display(chat_record)
        # 获取统计信息
        statistics = self.processor.get_chat_statistics(chat_record)
        return GetChatRecordOutputSchema(
            chat_record=chat_record,
            formatted_chat=formatted_chat,
            statistics=statistics
        )
